from playwright.sync_api import sync_playwright
import os
from apscheduler.schedulers.blocking import BlockingScheduler
from datetime import datetime
import requests

cookies = "_ga=GA1.2.257949950.1626079002; passport_csrf_token_default=67c4c80b25fe778ab9c3edb122727bce; passport_csrf_token=67c4c80b25fe778ab9c3edb122727bce; passport_auth_status=1f8526b932b6d3a2b3146b88b3305305%2C; passport_auth_status_ss=1f8526b932b6d3a2b3146b88b3305305%2C; sid_guard=56317bea1a04bbc07ef53ceabdd2cf76%7C1626079030%7C5184000%7CFri%2C+10-Sep-2021+08%3A37%3A10+GMT; uid_tt=67ff42a59f67555a47d44dd903d0f7e0; uid_tt_ss=67ff42a59f67555a47d44dd903d0f7e0; sid_tt=56317bea1a04bbc07ef53ceabdd2cf76; sessionid=56317bea1a04bbc07ef53ceabdd2cf76; sessionid_ss=56317bea1a04bbc07ef53ceabdd2cf76; n_mh=HhodOvSCt881-hub2AihH37mwAsfBDDDjG1DMgh1oew; MONITOR_WEB_ID=1b8643b0-3051-4a0f-9708-b42649870335; _gid=GA1.2.1976721800.1626677021"

headers = {
    "cookie": cookies,
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.164 Safari/537.36"
}


def run(playwright):
    browser = playwright.chromium.launch(headless=True, timeout=60000)
    context = browser.new_context(
        storage_state=os.path.join(os.path.dirname(os.path.realpath(__file__)), 'echone.json'))

    # Open new page
    page = context.new_page()

    # Go to https://juejin.cn/
    page.goto("https://juejin.cn/")

    if page.query_selector(".login-button"):
        return "COOKIE信息过期，请重新签到"

    # Click img[alt="echone的头像"]
    page.goto("https://juejin.cn/user/center/signin?from=avatar_menu")

    page.wait_for_selector(".code-calender .btn")
    signedin = page.query_selector(".code-calender .btn")
    if signedin:
        txt = signedin.inner_text()
        if txt == "立即签到":
            page.click("button.signin")
            page.wait_for_timeout(5000)
            context.close()
            browser.close()
            return "签到成功"
        else:
            context.close()
            browser.close()
            return txt
    context.close()
    browser.close()
    return "签到元素改变，请重新改写该代码"


def juejin_lottery():
    requests.post('https://api.juejin.cn/growth_api/v1/lottery/draw', headers=headers)


def juejin_sign():
    try:
        with sync_playwright() as playwright:
            return run(playwright)
    except Exception as e:
        print(e)
        return str(e)


def job():
    SERVER_KEY = "xxx"
    resp = juejin_sign()
    txt = f"执行时间：{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, 执行结果：{resp}"
    if resp != "今日已签到":
        requests.get(f"https://sctapi.ftqq.com/{SERVER_KEY}.send?title=掘金签到提醒&desp={txt}")
    print(txt)


if __name__ == '__main__':
    # 启动程序的时候默认执行一次
    job()
    scheduler = BlockingScheduler()
    # 每天执行3次防止出错
    scheduler.add_job(job, 'interval', hours=8)
    scheduler.start()
